package edu.bbk.muc.lifetracker.sensormanager;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.util.Log;
import edu.bbk.muc.lifetracker.common.Acceleration;
import edu.bbk.muc.lifetracker.common.Configuration;
import edu.bbk.muc.lifetracker.common.SensorsToUi;

/**
 * This class provides functionality to record speed acceleration, more
 * specifically the rate of change in speed in given direction.
 * 
 * @author irenatyler and romankirillov
 * 
 */

public class AccelerationRecorder extends SensorRecorder {

  /**
   * Listener for this acceleration sensor events.
   * @author irenatyler and romankirillov
   */
  class AccelerationSensorListener extends AbstractSensorListener {
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
      Log.d(getTag(),
          String.format(
              "SensorValues: lateral: %1$s, longitudinal: %2$s, vertical: %3$s",
              sensorEvent.values[0],
              sensorEvent.values[1],
              sensorEvent.values[2]));

      getSensorsToUi().onAccelerationChanged(
          sensorEvent.timestamp,
          new Acceleration(
              sensorEvent.values[0],
              sensorEvent.values[1],
              sensorEvent.values[2]));
    }
  }

  private static final int sensorType = Sensor.TYPE_ACCELEROMETER;

  private static final String TAG = "AccelerationRecorder";

  /**
   * Initialises this and parent class fields.
   * @param currentActivity Base application activity
   * @param callback Callback receiver for all sensor events
   */
  public AccelerationRecorder(Activity currentActivity, SensorsToUi callback) {
    super(currentActivity, callback);
    sensor = getSensorManager().getDefaultSensor(sensorType);
    Log.i(TAG, "AccelerationRecorder created");
  }

  @Override
  public void acceptNewConfiguration(Configuration configuration) {
    //check if acceleration sensor is enabled
    if (configuration.isAccelerationEnabled()) {
      doStart();
    } else {
      doStop();
    }
  }

  @Override
public AbstractSensorListener getListener() {
    if (this.listener == null) {
      setListener(new AccelerationSensorListener());
    }
    return this.listener;
  }

  @Override
  protected Sensor getSensor() {
    return this.sensor;
  }

  @Override
  protected int getSensorType() {
    return sensorType;
  }

  @Override
public String getTag() {
    return TAG;
  }

  @Override
  protected void setListener(AbstractSensorListener listener) {
    this.listener = listener;
  }
}
